// 云对象教程: https://uniapp.dcloud.net.cn/uniCloud/cloud-obj
// jsdoc语法提示教程：https://ask.dcloud.net.cn/docs/#//ask.dcloud.net.cn/article/129
const uniID = require('uni-id-common')
const utils = require('uni-utils')
module.exports = {
	_before: function () { // 通用预处理器
		const methodName = this.getMethodName()
		if(['getUser', 'loginSetUser', 'setUser'].includes(methodName) && !this.getUniIdToken()) {
			throw new Error('token不存在')
		}
		const clientInfo = this.getClientInfo()
		this.uniIDIns = uniID.createInstance({ // 创建uni-id实例，其上方法同uniID
			clientInfo
		})
		this.unicloud = uniCloud.database()
	},
	loginSetUser(data) {
		return new Promise((resolve, reject) => {
			this.unicloud.collection('uni-id-users').where({ _id: data.uid }).get().then(res => {
				if(res.data.length === 0) {
					reject({ code: 500, msg: '用户不存在' })
				} else {
					const result = res.data[0]
					if(result.nickName) {
						resolve({ code: 200, msg: '操作成功' })
					} else {
						this.unicloud.collection('uni-id-users').where({ _id: data.uid }).update({
							nickName: `${data.nickName}-${utils.generateRandomString(6)}`,
							avatar: data.avatar
						}).then(ret => {
							resolve({ code: 200, msg: '操作成功' })
						})
					}
				}
			}).catch(c => utils.captureCatch(c, resolve))
		})
	},
	setUser(data) {
		return new Promise((resolve, reject) => {
			const uid = data.uid
			if(!data.uid) {
				reject({ code: 500, msg: 'uid 为必填项' })
			}
			delete data.uid
			utils.isCheckToken(this.uniIDIns, this.getUniIdToken()).then(res => {
				return this.unicloud.collection('uni-id-users').where({ _id: uid }).get()
			}).then(res => {
				if(res.data.length === 0) {
					reject({ code: 500, msg: '用户不存在' })
				} else {
					return this.unicloud.collection('uni-id-users').where({ _id: uid }).update(data)
				}
			}).then(res => {
				resolve({ code: 200, msg: '操作成功' })
			})
			.catch(c => utils.captureCatch(c, resolve))
		})
	},
	getUser() {
		return new Promise((resolve) => {
			let obj = null
			utils.isCheckToken(this.uniIDIns, this.getUniIdToken()).then(res => {
				return this.unicloud.collection('uni-id-users').where({ _id: res.uid }).get()
			}).then(res => {
				const data = res.data[0]
				if(data.avatar) {
					obj = Object.assign({}, data)
					return uniCloud.getTempFileURL({
						fileList: [data.avatar]
					})
				} else {
					return Promise.resolve(data)
				}
			})
			.then(res => {
				if(obj) {
					const path = res.fileList[0].tempFileURL
					resolve({ code: 200, uid: obj._id, nickName: obj.nickName, avatar: path })
				} else {
					resolve({ code: 200, uid: data._id, nickName: data.nickName, avatar: data.avatar })
				}
			}).catch(c => utils.captureCatch(c, resolve))
		})
	}
}
